import React, { useEffect, useMemo, useState } from 'react';
import { Button, Card, message, Modal, Table } from 'antd';
import { deletePermission, fetchPermissionList } from '@/store/modules/permissionStore';
import { useDispatch, useSelector } from 'react-redux';
import type { Employee as Emp } from '@/type/employeeType';
import type { Permission as Per } from '@/type/permissionType';
import { useAppDispatch } from '@/hooks';

const Permission = () => {
  const dispatch = useDispatch();
  const appDispatch = useAppDispatch();
  const permissionTree = useSelector((state: any) => state.permissionStore.permissionTree);
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [edit, setEdit] = useState<boolean>(false);
  const title = useMemo(() => edit ? '编辑权限' : '添加权限', [edit]);
  const columns = [
    { title: '权限名称', dataIndex: 'name', key: 'name' },
    { title: '权限标识', dataIndex: 'code', key: 'code' },
    { title: '权限描述', dataIndex: 'description', key: 'description' },
    {
      title: '权限类型', render: (_: Per, record: Per) => {
        return (
          <>
            <span>{record.type === 1 ? '页面权限' : '按钮权限'}</span>
          </>
        );
      },
    },

    {
      title: '操作', render: (_: Per, record: Per) => {
        return (
          <>
            <Button type="primary" onClick={() => handleAdd(1, record.id)}>添加权限</Button>
            <Button type="primary" onClick={() => handleEdit(record)}>编辑权限</Button>
            <Button type="primary" danger onClick={() => handleDelete(record)}>删除权限</Button>
          </>
        );
      },
    },
  ];

  /**
   * @description 获取所有权限点的回调函数
   * */
  const fetchPermission = async () => {
    try {
      await dispatch(fetchPermissionList()).unwrap();
    } catch (rejectedValueOrSerializedError: any) {
      message.error(rejectedValueOrSerializedError);
    }
  };

  const handleDelete = async (record: Per) => {
    try {
      const deleteMessage = await appDispatch(deletePermission(record.id)).unwrap();
      await fetchPermission();
      message.success(deleteMessage);
    } catch (rejectedValueOrSerializedError: any) {
      message.error(rejectedValueOrSerializedError);
    }
  };


  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };


  const handleAdd = (type: number, pid: number) => {
    setIsModalOpen(true);
    setEdit(false);
  };

  const handleEdit = (record: Per) => {
    setIsModalOpen(true);
    setEdit(true);
  };

  useEffect(() => {
    fetchPermission();
  }, []);

  return (
    <div className="permission">
      <Card>
        <Button type="primary" onClick={() => handleAdd(1, 0)}>添加权限</Button>
        <Table rowKey="id" columns={columns} dataSource={permissionTree} bordered></Table>
      </Card>

      <Modal width={700} title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>

      </Modal>

    </div>
  );
};

export default Permission;
